package com.planet.events;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import com.planet.classes.EventHandler;
import com.planet.classes.Events;
import com.planet.classes.HighlightHandler;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

public class SplashActivity extends Activity {
	private Events _events;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        new ParseXML().execute();
	}
	
	private class ParseXML extends AsyncTask<Void, Void, Void> {
		private ArrayList<Integer> _highlights;
		@Override
		protected Void doInBackground(Void ...params){
			try {
				System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
				XMLReader xmlReader = XMLReaderFactory.createXMLReader();
				
				EventHandler eventHandler = new EventHandler(); 
				xmlReader.setContentHandler(eventHandler);
				URL url = new URL("http://www.planet.tt/android/iphone_xml.php");
				URLConnection conn = url.openConnection();
				InputStream in = conn.getInputStream();
				xmlReader.parse(new InputSource(in));
				
				_events = eventHandler.GetEvents();
				
				HighlightHandler highlightHandler = new HighlightHandler();
				xmlReader.setContentHandler(highlightHandler);
				url = new URL("http://www.planet.tt/android/highlight_xml.php");
				conn = url.openConnection();
				in = conn.getInputStream();
				xmlReader.parse(new InputSource(in));
				
				_highlights = highlightHandler.GetHighlights();
				
				_events.SetHighlights(_highlights);
				
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void params){
			Bundle bundle = new Bundle();
            bundle.putSerializable("Events", _events);
            Intent newIntent = new Intent(getApplicationContext(), StartActivity.class);
            newIntent.putExtras(bundle);
            startActivity(newIntent);
            finish();
		}
	}
}
